<!--
/**
* Author: txj
* Date: 2023年8月10日11:12:20
* Desc: 点餐页
*/
-->
<template>
  <yy-page custom-class="h100p overflow-hide" hasTab>
    <!-- #ifdef MP-WEIXIN || MP-ALIPAY -->
    <yy-navbar :border="false" left-icon-color="#fff" :auto-back="true" title="点餐" title-style="color:#fff" :show-left="false"></yy-navbar>
    <!-- #endif-->
    <view class="main">
      <view class="flex-b pd30 flex-m">
        <view class="flex-1">
          <view class="fs26 fc3">{{ cinemaInfo.cinemaName }} {{ getDistanceTop() }}</view>
          <view class="fs24 fc9 mt15">{{ cinemaInfo.address }}</view>
        </view>
        <view v-if="isSingleModel" class="icon-change" @click="openCinema"></view>
      </view>
      <view class="page-body" :style="'height:' + height + 'px'">
        <scroll-view class="nav-left" scroll-y :style="'height:' + height + 'px'" :scroll-top="scrollLeftTop" scroll-with-animation>
          <view class="nav-left-item" @click="categoryClickMain(index)" :key="index" :class="index == categoryActive ? 'active' : ''" v-for="(item, index) in mallList">
            <view>{{ item.name }} </view>
            <image class="w70 h70 mt10" :src="item.icon" />
          </view>
          <view class="nav-left-item-end"></view>
        </scroll-view>
        <scroll-view class="nav-right" scroll-y :scroll-top="scrollTop" @scroll="scroll" :style="'height:' + height + 'px'" scroll-with-animation>
          <view v-for="(item, index) in mallList" :key="index" class="box">
            <view class="ml20 mt30 mb10 fc6">{{ item.name }}</view>
            <mall-buy-item :id="i == 0 ? 'first' : ''" v-for="(item, i) in item.merchandiseList" :key="i" :item-data="item" v-model="item.num"> </mall-buy-item>
          </view>
        </scroll-view>
      </view>
      <view v-if="couponsNum != '0'" class="coupon" @click="openCoupon" :style="{ bottom: 122 + tabHeight + 'rpx' }">
        <view class="fs34 b fc-yellow">{{ couponsNum }}<text class="fs22 fc3 ml5">张商品券可用</text></view>
        <view class="coupon-btn">去使用</view>
      </view>
      <view class="bottom-view" :style="{ bottom: 12 + tabHeight + 'rpx' }">
        <view class="num" v-if="showPrice">{{ getNum }}</view>

        <view class="image mr30" :class="showPrice ? '' : 'image-no'" @click="openShopCar"> </view>
        <view v-if="!showPrice" class="fc-white fs30"> {{ showPrice ? '' : '未选购商品' }}</view>
        <price v-if="showPrice" :price="getPrice" unit-size="30" price-size="42" color="#fff"></price>
        <view class="flex-1"></view>
        <view @click="toBuy()" class="btn" :class="showPrice ? '' : 'btn-no'">结算</view>
      </view>
      <view class="shopcar" v-if="showShopCar" :style="{ bottom: tabHeight + 'rpx' }">
        <view class="close" @click="() => (showShopCar = false)"></view>
        <view class="list-shopcar">
          <mall-buy-item-by-shop class="w100p" use-coupon="true" v-for="(item, i) in getShopCarCoupon" :key="i" :item-data="item" @deleteCoupon="deleteCoupon" v-model="item.num">
          </mall-buy-item-by-shop>
          <view class="w100p" v-for="(itemMall, indexMall) in mallList" :key="indexMall">
            <view class="w100p" v-for="(item, i) in itemMall.merchandiseList" :key="i">
              <mall-buy-item-by-shop v-if="item.num > 0" class="w100p" :item-data="item" v-model="item.num"> </mall-buy-item-by-shop>
            </view>
          </view>
        </view>
      </view>
      <view class="cinema" v-if="showCinema" :style="{ bottom: tabHeight + 'rpx' }">
        <view class="list-cinema">
          <view class="fs36 fc3">请选择点餐影城</view>
          <view
            class="item-cinema"
            v-for="(item, index) in cinemaList"
            :class="item.cinemaId === checkCinema.cinemaId ? '' : 'item-cinema-noClick'"
            :key="index"
            @click="saveCinema(item)"
          >
            <view class="flex-b">
              <view class="fc3 fs30">{{ item.cinemaName }}</view>
              <view v-if="item.distance" class="fs24 fc6">{{ getDistance(item.distance) }}</view>
            </view>
            <view class="fs24 fc6 mt20">{{ item.address }}</view>

            <view class="list-icon" v-if="item.hasFilm || (item.distance && index === 0)">
              <view v-for="(itemFilm, indexFilm) in item.unShowFilm" :key="indexFilm" class="item-icon">已购票：{{ itemFilm.startTime + '  《' + itemFilm.filmName + '》' }}</view>
              <span class="item-icon" v-if="item.distance && index === 0"> 距离最近</span>
            </view>
          </view>
          <view class="cinema-btn" @click="selectCinema">去点餐</view>
        </view>
      </view>
      <view v-if="showTime" class="time flex-col flex-m">
        <image style="height: 240rpx; width: 320rpx; margin-top: 150rpx" src="https://zmax-public-js.oss-cn-hangzhou.aliyuncs.com/applet/img/my/goods-no-time.png"></image>
        <view class="mt50 fc-gray">未到点餐时间</view>
        <view class="btn mt70" @click="reSet">刷新</view>
      </view>
    </view>
  </yy-page>
</template>

<script>
  import Price from '@/components/Price'
  import classifyData from './data'
  import { locSelmallCoupon, locSelmallData } from '@/utils/locStore/data'
  import MallBuyItem from './mallBuyItem.vue'
  import MallBuyItemByShop from './mallBuyItemByShop.vue'
  import { deep } from '@/utils'
  import { mapGetters } from 'vuex'
  export default {
    name: 'mall-buy-main',
    components: { Price, MallBuyItem, MallBuyItemByShop },
    data() {
      let tabHeight = 100
      if (uni.$u.sys().safeAreaInsets && uni.$u.sys().safeAreaInsets.bottom) {
        tabHeight = Math.abs(uni.$u.sys().safeAreaInsets.bottom) + 100
      }
      console.log('tabHeight', tabHeight)
      return {
        showTime: false,
        mallSet: {},
        tabHeight: tabHeight,
        checkCinema: {},
        cinemaList: [],
        coupons: [],
        couponsNum: 0,
        showCinema: this.$auth.getSingleModel(),
        showShopCar: false,
        num: 0,
        height: 0,
        categoryActive: 0,
        scrollTop: 0,
        scrollLeftTop: 0,
        // scrollHeight: 0,
        mallList: [],
        arr: [0, 584, 1168, 1752, 2336, 2805, 3274, 3858, 4442, 4911, 5380, 5734, 6203, 6672, 7017], //初始值，后边计算会根据手机适配覆盖
        leftItemHeight: 51, //49行会计算出新值进行覆盖
        navLeftHeight: 0, //左边scroll-view 内层nav的总高度
        diff: 0, //左边scroll-view 内层nav的总高度与视口之差
        tabBarHeight: 0 //如果此页面为Tab页面，自己改变高度值,,一般tab高度为51
      }
    },
    created() {
      //如果你的分类数据为后台异步获取请  将下方代码放置你的数据回调中
      // this.$nextTick(()=>{
      //  this.getHeightList();
      // })
    },
    onLoad() {
      locSelmallCoupon.remove() //清空选券数据
      locSelmallData.remove() //清空点餐数据
      this.height = uni.getSystemInfoSync().windowHeight - this.tabBarHeight
      this.getData()
      this.updateCinema()
    },

    onShow() {
      this.getSet()
      if (uni.getStorageSync('reDataMallBuy')) {
        this.$msg.toast(uni.getStorageSync('reDataMallBuy'))
        uni.removeStorageSync('reDataMallBuy')
        this.refreshData()
      }

      uni.setStorageSync('fromRealName', '1')
      this.coupons = locSelmallCoupon.get() || []
      console.log('onShow', this.coupons)
    },
    onReady() {
      // this.getHeightList()
    },
    methods: {
      updateCinema() {
        console.log('updateCinema mallbuymain')
        // 更新影院信息
        this.$auth.getCinemaInfo(true, 'update')
      },
      reSet() {
        this.getSet()
      },
      getSet() {
        uni.$api.orderFood.getSet({ cinemaId: this.$auth.getLocCinemaInfo().cinemaId }).then((res) => {
          this.mallSet = res
          const canBuy = this.$utils.isDuringDate(this.mallSet.startTime, this.mallSet.endTime)
          if (canBuy) {
            this.showTime = false
          } else {
            this.showTime = true
          }
        })
      },
      openShopCar() {
        if (this.showPrice) {
          this.showShopCar = true
        }
      },
      openCinema() {
        this.showCinema = true
      },
      getHeightList() {
        const selectorQuery = uni.createSelectorQuery()
        selectorQuery.selectAll('.nav-left-item').boundingClientRect((rects) => {
          if (rects.length > 0) {
            this.leftItemHeight = rects[0].height
          }
          this.navLeftHeight = this.leftItemHeight * this.mallList.length
          this.diff = this.navLeftHeight - this.height
        })
        selectorQuery
          .selectAll('.box')
          .boundingClientRect((rects) => {
            const arr = [0]
            let top = 0
            rects.forEach((rect) => {
              //                  rect.id      // 节点的ID
              //                  rect.dataset // 节点的dataset
              //                  rect.left    // 节点的左边界坐标
              //                  rect.right   // 节点的右边界坐标
              //                  rect.top     // 节点的上边界坐标
              //                  rect.bottom  // 节点的下边界坐标
              //                  rect.width   // 节点的宽度
              //                  rect.height  // 节点的高度
              top += rect.height
              arr.push(top)
            })
            console.log(arr)
            this.arr = arr
          })
          .exec()
      },
      scroll(e) {
        if (this.timeoutId) {
          clearTimeout(this.timeoutId)
        }
        this.timeoutId = setTimeout(() => {
          //节流
          this.scrollHeight = e.detail.scrollTop + 1
          // +this.height/2
          //+1不要删除，解决最后一项某种情况下翻到底部，左边按钮并不会切换至最后一个
          //若想使切换参考线为屏幕顶部请删除 this.height/2
          for (let i = 0; i < this.arr.length; i++) {
            const height1 = this.arr[i]
            const height2 = this.arr[i + 1]

            if (!height2 || (this.scrollHeight >= height1 && this.scrollHeight < height2)) {
              this.categoryActive = i
              //80为单item高度
              this.diff > 0 && (this.scrollLeftTop = this.categoryActive * 80)
              // (this.scrollLeftTop = Math.round(
              //   (this.categoryActive * this.diff) / (this.mallList.length - 1)
              // ))
              return false
            }
          }
          this.categoryActive = 0
          this.timeoutId = undefined
        }, 10)
      },
      categoryClickMain(index) {
        this.categoryActive = index
        this.scrollTop == this.arr[index] ? (this.scrollTop = this.scrollTop + 1) : (this.scrollTop = this.arr[index]) //防止两次相等造成点击不触发滚动时间
      },
      changeNum(item) {
        console.log(item)
      },
      deleteCoupon(list) {
        console.log(list)
        list.forEach((item) => {
          this.coupons = this.coupons.filter((i) => {
            return item !== i.code
          })
          console.log('forEach', this.coupons)
        })
        console.log('locSelmallCoupon', this.coupons)
        locSelmallCoupon.set(this.coupons)
      },
      selectCinema() {
        this.$auth.saveCinemaInfo(this.checkCinema)
        this.showCinema = false
      },
      saveCinema(item) {
        this.checkCinema = item
      },
      openCoupon() {
        this.$tools.navigateTo('/pagesOrder/mallCoupon/index')
      },
      toBuy() {
        if (this.$auth.getIslogin()) {
          const buyList = [...this.getShopCarCoupon, ...this.getShopCarMall]
          if (buyList.length > 0) {
            locSelmallData.remove()
            locSelmallData.set(buyList)
            this.$tools.navigateTo('/pages/mall/mallPay')
          } else {
            this.$msg.toast('请选择商品')
          }
        } else {
          this.$tools.navigateTo(`/pages/login/index`)
        }
      },
      getCinemaList() {
        const locationAreaInfo = this.$auth.getLoctionAreaInfo() || {}
        console.log('locationAreaInfo', locationAreaInfo)
        const data = {}
        if (locationAreaInfo && locationAreaInfo.lng) {
          data.longitude = locationAreaInfo.lng.toString()
          data.latitude = locationAreaInfo.lat.toString()
        }

        uni.$api.orderFood.getCinemaList(data).then((res) => {
          this.cinemaList = res
          res.forEach((item) => {
            if (item.cinemaId === this.$auth.getLocCinemaInfo().cinemaId) {
              this.checkCinema = item
            }
          })
        })
      },
      getMenuList() {
        uni.$api.orderFood.getMenuList({ cinemaId: this.cinemaInfo.cinemaId }).then((res) => {
          this.mallList = []
          res.forEach((item) => {
            if (item.merchandiseList.length > 0) {
              item.merchandiseList.forEach((i) => {
                i.num = 0
              })
              this.mallList.push(item)
            }
            // else {
            //   item.merchandiseList.push({ name: 123 })
            //   this.mallList.push(item)
            // }
          })
          this.$nextTick(() => {
            this.getHeightList()
          })
        })
      },
      getMerchandiseCouponList() {
        if (this.$auth.getIslogin()) {
          const query = {
            version: '2',
            isPage: '2',
            cinemaId: this.cinemaInfo.cinemaId
          }
          uni.$api.coupon.getMerchandiseCouponList(query).then((res) => {
            this.couponsNum = res.count
          })
        }
      },
      getData() {
        this.getCinemaList()
        this.refreshData()
      },
      refreshData() {
        locSelmallCoupon.remove()
        this.coupons = []
        this.getMenuList()
        this.getMerchandiseCouponList()
      },
      getDistance(distance) {
        return this.$utils.getDistanceTxt(distance)
      },
      getDistanceTop() {
        const { lat, lng } = this.$auth.getLoctionAreaInfo()

        const distance = this.$utils.getDistance(lat, lng, this.cinemaInfo.latitude, this.cinemaInfo.longitude) // 计算距离
        let text = ''
        if (lat) {
          text = '(' + this.$utils.getDistanceTxt(distance) + ')'
        }
        return text
      },
      getStartTime(startTime) {
        return this.$utils.dateDescfrt(startTime) + '  ' + this.$utils.dateFmt(startTime, 'HH:mm')
      }
    },
    computed: {
      ...mapGetters(['cinemaInfo']),

      getShopCarMall() {
        const shopCarMall = []
        this.mallList.forEach((mallItem) => {
          mallItem.merchandiseList.forEach((i) => {
            if (i.num > 0) {
              shopCarMall.push(i)
            }
          })
        })
        return shopCarMall
      },
      getShopCarCoupon() {
        console.log('shopCarCoupon')
        const shopCarCoupon = []
        const list = deep(this.mallList)
        if (this.coupons && this.coupons.length > 0) {
          this.coupons.forEach((item) => {
            list.forEach((mallItem) => {
              mallItem.merchandiseList.forEach((i) => {
                if (i.merchandiseId === item.merchandiseId) {
                  if (!i.coupons) {
                    i.coupons = []
                    shopCarCoupon.push(i)
                  }
                  i.coupons.push(item.code)
                }
              })
            })
          })
        }
        console.log('shopCarCoupon', shopCarCoupon)
        return shopCarCoupon
      },
      showPrice() {
        let show = false
        if (this.getPrice !== 0) {
          show = true
        }
        if (this.coupons && this.coupons.length > 0) {
          show = true
        }
        return show
      },
      getPrice() {
        let price = 0
        this.mallList.forEach((item) => {
          item.merchandiseList.forEach((i) => {
            price += i.num * i.salePrice
          })
        })
        return price
      },
      getNum() {
        console.log('getNum', this.coupons)
        let num = 0
        if (this.coupons && this.coupons.length > 0) {
          num += this.coupons.length
        }

        this.mallList.forEach((item) => {
          item.merchandiseList.forEach((i) => {
            num += i.num
          })
        })
        return num
      },
      isSingleModel() {
        console.log('this.$auth.getSingleModel()', this.$auth.getSingleModel())
        return this.$auth.getSingleModel()
      }
    },
    watch: {
      showPrice(i) {
        if (!i) {
          this.showShopCar = false
        }
      },
      cinemaInfo: {
        handler(v, o) {
          console.log('handler', v, o)
          //切换影城清除用券数据
          if (v.cinemaId != o.cinemaId) {
            this.refreshData()
          }
        },
        deep: true
      }
    }
  }
</script>

<style lang="scss" scoped>
  .main {
    height: 100%;
    width: 100%;
    overflow: hidden;
    position: relative;
    .icon-change {
      background: url('https://public-oss-file.zmaxfilm.com/applet/img/film-oxygen-uniapp/icon-change.png') no-repeat;
      background-size: 100%;
      width: 40rpx;
      height: 32rpx;
    }
    .scroll {
      flex: 1;
      overflow-y: scroll;
    }
  }
  .page-body {
    display: flex;
    background: #fff;
    overflow: scroll;
  }

  .nav {
    display: flex;
    width: 100%;
  }

  .nav-left {
    width: 160rpx;
    background: #f0f0f0;
  }
  .nav-right {
    width: 75%;
  }
  .nav-left-item-end {
    color: #666666;
    height: calc(100% - 160rpx);
  }
  .nav-left-item {
    width: 160rpx;
    height: 160rpx;
    flex-direction: column;
    font-size: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666666;
  }
  // .nav-left-item:last-child {
  //   border: none;
  //   height: 100vh;
  //   justify-content: flex-start;
  //   padding-top: 20rpx;
  // }
  .active {
    color: #333333;
    background: #fff;
    border-right: 0;
  }

  .box {
    display: block;
    overflow: hidden;
    // border-bottom: 20rpx solid #f3f3f3;
    /* min-height: 100vh; 
    /*若您的子分类过少想使得每个子分类占满屏请放开上边注视 */
  }
  .box:last-child {
    border: none;
    min-height: 100%;
  }
  .nav-right-item {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    padding: 20rpx;
    background: #fff;
    .image {
      margin-right: 10rpx;
      width: 160rpx;
      height: 160rpx;
    }
    .item-money {
      display: flex;
      align-items: flex-end;
      justify-content: space-between;
      flex-direction: column;
      padding-bottom: 10rpx;
    }
  }

  ::-webkit-scrollbar {
    /*取消小程序的默认导航条样式*/
    width: 0;
    height: 0;
    color: transparent;
  }
  .coupon {
    position: fixed;
    left: 20rpx;
    background: url('https://public-oss-file.zmaxfilm.com/applet/img/film-oxygen-uniapp/mall-buy-coupon.png') no-repeat;
    background-size: 100%;
    width: 220rpx;
    height: 122rpx;
    display: flex;
    align-items: center;
    flex-direction: column;
    padding-top: 10rpx;
    .coupon-btn {
      width: 90rpx;
      text-align: center;
      line-height: 30rpx;
      margin-top: 5rpx;
      height: 30rpx;
      background: #fa5a0b;
      border-radius: 14rpx;
      font-size: 18rpx;
      color: #ffffff;
    }
  }
  .bottom-view {
    z-index: 98;
    display: flex;
    align-items: center;
    position: fixed;
    left: 10rpx;
    right: 10rpx;
    // width: calc(100% - 20rpx);
    // margin: 10rpx;
    height: 100rpx;
    background: #333333;
    border-radius: 18rpx;
    .btn {
      width: 218rpx;
      height: 100rpx;
      background: linear-gradient(135deg, #55baff 0%, #23e6d8 100%);
      border-radius: 18rpx;
      margin-left: 20rpx;
      font-size: 36rpx;
      color: #ffffff;
      text-align: center;
      line-height: 100rpx;
    }
    .btn-no {
      background: #999999;
    }
    .num {
      position: absolute;
      width: 40rpx;
      height: 40rpx;
      text-align: center;
      background: #fa5a0b;
      border-radius: 50%;
      font-size: 30rpx;
      color: #ffffff;
      line-height: 40rpx;
      top: -10rpx;
      left: 120rpx;
    }

    .image {
      background: url('https://public-oss-file.zmaxfilm.com/applet/img/film-oxygen-uniapp/icon-shopCar.png') no-repeat;
      background-size: 100%;
      height: 116rpx;
      margin: 0 0 30rpx 30rpx;
      width: 120rpx;
    }
    .image-no {
      background-image: url('https://public-oss-file.zmaxfilm.com/applet/img/film-oxygen-uniapp/icon-shopCar-no.png');
    }
  }

  .time {
    z-index: 100;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #f2f2f2;
    .btn {
      width: 218rpx;
      height: 100rpx;
      background: linear-gradient(135deg, #55baff 0%, #23e6d8 100%);
      border-radius: 18rpx;
      font-size: 36rpx;
      color: #ffffff;
      text-align: center;
      line-height: 100rpx;
    }
  }
  .shopcar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.4);
    .close {
      top: 0;
      height: 100%;
      position: absolute;
      left: 0;
      right: 0;
    }
    .list-shopcar {
      display: flex;
      align-items: center;
      flex-direction: column;
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      max-height: 50vh;
      min-height: 300rpx;
      overflow-y: scroll;
      background: #ffffff;
      border-radius: 30rpx 30rpx 0rpx 0rpx;
      padding: 30rpx 30rpx 120rpx;
      .item-shopcar {
      }
    }
  }
  .cinema {
    z-index: 99;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.4);
    .list-cinema {
      display: flex;
      align-items: center;
      flex-direction: column;
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      max-height: 70vh;
      min-height: 300rpx;
      overflow-y: scroll;
      background: #ffffff;
      border-radius: 30rpx 30rpx 0rpx 0rpx;
      padding: 30rpx;
      .item-cinema {
        width: calc(100% - 60rpx);
        background: #ffffff;
        border: 2rpx solid #44c9f2;
        border-radius: 20rpx;
        padding: 30rpx;
        margin-top: 20rpx;
        .list-icon {
          margin-top: 20rpx;
          height: 40rpx;
          display: flex;
          overflow-x: scroll;
          white-space: nowrap;
          box-sizing: border-box;
          .item-icon {
            line-height: 40rpx;
            height: 40rpx;
            background: #ffa800;
            border-radius: 8rpx;
            padding: 0rpx 10rpx;
            margin-right: 20rpx;
            color: white;
            font-size: 22rpx;
          }
        }
      }
      .item-cinema-noClick {
        border: 1rpx solid #dadada;
      }
      .cinema-btn {
        margin-top: 24rpx;
        width: 100%;
        height: 100rpx;
        background: linear-gradient(135deg, #55baff 0%, #23e6d8 100%);
        border-radius: 20rpx;
        font-size: 36rpx;
        color: #ffffff;
        text-align: center;
        line-height: 100rpx;
      }
    }
  }
</style>
